<script setup>
import {ref, reactive, onMounted, computed} from 'vue'
import {ElMessage} from 'element-plus'
import {getKnowledgeCategories, httpKnowledgeList, httpFiles, updateUseTimes} from '@/api/knowledge.js'
import Pagination from '@/components/pagination/index.vue'
import useCollectStore from '@/stores/collect.js'
import useKnowledgeStore from '@/stores/knowledge.js'
import {useRouter} from 'vue-router'
import {formatFileSize} from '@/utils/index.js'
import DocumentViewer from '@/components/document-viewer/index.vue'
import FireFilled from '@/icons/FireFilled.vue'
const imagePrefix = import.meta.env.VITE_IMAGE_SUFFIX
const collectStore = useCollectStore()
const knowledgeStore = useKnowledgeStore()
const router = useRouter()

onMounted(() => {
  init()
  setMainHeight()
})
const loading = ref(false)
const allCategories = ref([])
const knowledgeList = ref([])
const knowledgeTotal = ref(0)
const query = reactive({
  sort_id: 0,
  page: 1,
  keyword: '',
  limit: 20
})

const useKnowledge = (item) => {
  if (knowledgeStore.getKnowledge().id === item.id) {
    knowledgeStore.setKnowledge(0, '')
  } else {
    knowledgeStore.setKnowledge(item.id, item.name)
    updateUseTimes(item.id).catch(() => {})
    router.push('/chat?add=1')
  }
}

const allAvatars = computed(() => {
  return knowledgeList.value.map(item => {
    return imagePrefix + item.avatar
  })
})

const init = async () => {
  loading.value = true
  await getCategories(false)
  await collectStore.getKnowledgeCollects()
  await getList(false)
  loading.value = false
}

const getCategories = async (showLoading = true) => {
  if (showLoading) loading.value = true
  const response = await getKnowledgeCategories().catch(() => null)
  if (showLoading) loading.value = false
  if (!response) return
  let {list} = response
  list = [
    {
      id: 0,
      sort_name: '全部'
    },
    {
      id: -1,
      sort_name: '我的收藏'
    }
  ].concat(list)
  allCategories.value = list.map(item => {
    return {
      id: item.id,
      name: item.sort_name
    }
  })
}

const changeCategory = () => {
  query.page = 1
  getList()
}

const getList = async (showLoading = true) => {
  if (showLoading) loading.value = true
  const response = await httpKnowledgeList({...query}).catch(() => null)
  if (showLoading) loading.value = false
  if (!response) return
  const {list, total} = response
  knowledgeList.value = list
  knowledgeTotal.value = total
}

let collectTimer = null

const handleCollect = async (id) => {
  if (collectTimer !== null) {
    clearTimeout(collectTimer)
  }
  collectTimer = setTimeout(() => {
    collectStore.collectKnowledge(id)
    collectTimer = null
  }, 500)
}

const files = ref([])
const fileTotal = ref(0)
const list_loading = ref(false)
const fileShow = ref(false)
const knowledgeName = ref('')
const params = reactive({
  knowledge_id: 0,
  keyword: '',
  page: 1,
  limit: 20,
  status: 2
})

const showFiles = (id, kn) => {
  params.knowledge_id = id
  params.keyword = ''
  params.limit = 20
  params.page = 1
  files.value = []
  fileShow.value = true
  knowledgeName.value = kn
  getFiles()
}

const handleFilter = () => {
  params.page = 1
  getFiles()
}

const getFiles = async () => {
  list_loading.value = true
  const response = await httpFiles({...params}).catch(() => null)
  list_loading.value = false
  if (!response) {
    return
  }
  const {list, count} = response
  files.value = list
  fileTotal.value = count
}

const showFileEnable = ref(false)
const showFileUrl = ref('')
const showFileName = ref('')
const showFileExt = ref('')

const getFileExt = (filename) => {
  const name_arr = filename.split('.')
  if (name_arr.length <= 1) {
    return '._'
  } else {
    return '.' + name_arr[name_arr.length - 1]
  }
}

const downloadFile = (item, preview = false) => {
  const host = import.meta.env.VITE_BASE_API
  const url = host + `/knowledge/download-docs?knowledge_id=${params.knowledge_id}&file_name=${item.file_name}&preview=${preview ? 1 : 0}`
  if (!preview) {
    window.open(url)
  } else {
    showFileExt.value = getFileExt(item.file_name)
    showFileName.value = item.file_name
    showFileUrl.value = url
    showFileEnable.value = true
  }
}

const mainHeight = ref(document.body.clientHeight)

const setMainHeight = () => {
  window.onresize = () => {
    mainHeight.value = document.body.clientHeight
  }
}

</script>

<template>
  <div class="pw-100 vh-100 knowledge-bg knowledge-base">
    <el-tabs v-model="query.sort_id" @tab-change="changeCategory">
      <el-tab-pane
          v-for="(item) in allCategories"
          :label="item.name"
          :name="item.id"
      ></el-tab-pane>
    </el-tabs>
    <div>
      <el-input
          prefix-icon="Search"
          v-model="query.keyword"
          @keyup.native.enter="changeCategory"
          maxlength="32"
          clearable
          placeholder="搜索知识库"
          class="w-300 margin-left-10"
      />
      <el-button class="margin-left-10" icon="Search" type="primary" @click="changeCategory">搜索</el-button>
    </div>
    <div v-loading="loading" class="padding-10 knowledge-box">
      <el-row :gutter="20" v-if="knowledgeList.length">
        <el-col
            v-for="(item, index) in knowledgeList"
            :key="index"
            :xs="12"
            :sm="12"
            :md="8"
            :lg="8"
            :xl="6"
        >
          <div class="flex justify-content-center item-kno border-radius margin-bottom-20 padding-15">
            <div class="w-50 text-center">
              <el-image
                  fit="cover"
                  :src="imagePrefix + item.avatar"
                  :preview-src-list="allAvatars"
                  :initial-index="index"
                  class="w-50 h-50"
              />
              <el-button
                  class="margin-top-10"
                  size="small"
                  :type="knowledgeStore.getKnowledge().id === item.id ? 'danger' : 'primary'"
                  plain
                  @click="useKnowledge(item)"
              >
                {{knowledgeStore.getKnowledge().id === item.id ? '取消' : '使用'}}
              </el-button>
            </div>
            <div class="knowledge-info pointer" @click="showFiles(item.id, item.name)">
              <div class="text-ellipsis title" :title="item.name">
                <el-text class="font-size-2xl font-bold">{{ item.name }}</el-text>
              </div>
              <el-tooltip
                  effect="dark"
              >
                <template #content>
                  <div style="max-width: 400px;">{{ item.description }}</div>
                </template>
                <div class="description flex align-items-center">
                  <div class="desc-b">
                    <el-text>{{ item.description }}</el-text>
                  </div>
                </div>
              </el-tooltip>
              <div class="view flex align-items-center">
                <el-icon style="color: var(--el-color-danger)"><FireFilled/></el-icon>
                <span class="font-size-xs margin-left-5">{{item.select_number}}</span>
                <el-tooltip
                  effect="dark"
                  content="文件下载次数"
                >
                  <el-icon class="margin-left-30"><component is="Download"/></el-icon>
                </el-tooltip>
                <span class="font-size-xs margin-left-5">{{item.download_times}}</span>
              </div>
            </div>
            <div
                class="collection collected"
                @click="handleCollect(item.id)"
                v-if="collectStore.isCollected(item.id)"
            >
              <el-icon>
                <component is="StarFilled"></component>
              </el-icon>
            </div>
            <div
                class="collection"
                @click="handleCollect(item.id)"
                v-else
            >
              <el-icon>
                <component is="Star"></component>
              </el-icon>
            </div>
          </div>
        </el-col>
      </el-row>
      <el-empty description="暂无知识库" v-else/>
      <pagination
          :total="knowledgeTotal"
          v-model:page="query.page"
          v-model:limit="query.limit"
          @pagination="getList"
      />
    </div>
  </div>
  <el-dialog
      v-model="fileShow"
      width="80vw"
      top="5vh"
      :close-on-click-modal="false"
      :title="`《${knowledgeName}》文件列表`"
      center
  >
    <div class="margin-bottom-20">
      <el-input
          class="w-300"
          placeholder="搜索文件名称"
          clearable
          maxlength="100"
          v-model="params.keyword"
          @keyup.native.enter="handleFilter"
      />
      <el-button
          class="margin-left-10"
          type="primary"
          icon="Search"
          @click="handleFilter"
          :loading="list_loading"
      >搜索
      </el-button>
    </div>
    <el-table
        class="header-lighter"
        :data="files"
        stripe
        border
        :max-height="mainHeight - 270"
        highlight-current-row
        show-overflow-tooltip
        fit
        v-loading="list_loading"
    >
      <el-table-column type="selection" width="40"/>
      <el-table-column
          width="60"
          label="序号"
      >
        <template #default="{$index}">
          <span>{{ $index + 1 }}</span>
        </template>
      </el-table-column>
      <el-table-column
          label="文件名"
          min-width="300"
          prop="file_name"
      />
      <el-table-column
          label="文件大小"
          min-width="120"
      >
        <template #default="scope">
          <span>{{ formatFileSize(scope.row.file_size) }}</span>
        </template>
      </el-table-column>
      <el-table-column
          label="下载次数"
          min-width="100"
          prop="download_times"
      />
      <el-table-column label="创建时间" width="180">
        <template #default="scope">{{ scope.row.created_at.replace('T', ' ') }}</template>
      </el-table-column>
      <el-table-column label="操作" width="160" fixed="right">
        <template #default="scope">
          <el-button
              type="primary"
              icon="Download"
              link
              @click="downloadFile(scope.row)"
              :loading="loading"
          >下载
          </el-button>
          <el-button
              type="primary"
              icon="View"
              link
              @click="downloadFile(scope.row, true)"
              :loading="loading"
          >预览
          </el-button>
        </template>
      </el-table-column>
    </el-table>
    <pagination
        :total="fileTotal"
        v-model:limit="params.limit"
        v-model:page="params.page"
        @pagination="getFiles"
    />
  </el-dialog>
  <document-viewer :file-name="showFileName" :ext="showFileExt" v-model:show="showFileEnable" :url="showFileUrl"/>
</template>

<style scoped lang="scss">
.knowledge-bg {
  background-color: var(--el-bg-color);
  position: absolute;
  left: 0;
  top: 0;
  padding: 20px;
}

.item-kno {
  background: var(--el-bg-color);
  transition: color 0.2s, background-color 0.2s;
  box-shadow: 0 0 6px rgba(0, 0, 0, 0.24);
  position: relative;
}

.dark {
  .item-kno {
    background: var(--el-color-info-light-9);
    box-shadow: var(--el-box-shadow-lighter);
  }
}

.knowledge-box {
  margin-top: 10px;
  overflow-y: auto;
  overflow-x: hidden;
  height: calc(100vh - 116px);
}
.knowledge-base {
  .knowledge-info {
    width: calc(100% - 50px);
    padding-left: 12px;

    .description {
      height: 50px;
      overflow: hidden;
      .desc-b {
        max-height: 48px;
        display: -webkit-box;
        overflow: hidden;
        text-overflow: ellipsis;
        -webkit-line-clamp: 2;
        -webkit-box-orient: vertical;
      }
    }

    .title {
      width: calc(100% - 30px);
    }
    .view {
      color: var(--el-color-info);
      position: relative;
      top: 5px;
    }
  }

  .collection {
    width: 20px;
    height: 20px;
    position: absolute;
    right: 10px;
    top: 10px;
    font-size: 20px;
    cursor: pointer;

    &.collected {
      color: var(--el-color-danger);
      font-size: 26px;

      i {
        left: -3px;
        top: -3px;
      }
    }
  }
}
</style>